#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <wait.h>

#define MEMSIZE 1024

int main(int argc, char * argv[])
{
    pid_t pid;
    int shmid;
    char *ptr;

    if((shmid = shmget(IPC_PRIVATE, MEMSIZE, 0666)) < 0)
    {
        perror("shmget");
        exit(1);
    }
    pid = fork();
    if(pid < 0)
    {

        perror("fork");
        exit(1);
    }
    else if(pid == 0)
    {
        //w
        ptr = shmat(shmid, NULL, 0);
        if(ptr == (void *)-1)
        {
            perror("shmat");
            exit(1);
        }
        strcpy(ptr, "hello!");
        shmdt(ptr);
        exit(0);
    }
    else
    {
        //r
        ptr = shmat(shmid, NULL, 0);
        if(ptr == (void *)-1)
        {
            perror("shmat");
            exit(1);
        }
        wait(NULL);
        puts(ptr);
        shmdt(ptr);
        shmctl(shmid, IPC_RMID, NULL);
        exit(0);
    }
}